package com.jydd.singlekotlinmvvm.comm.feature.login

import androidx.lifecycle.viewModelScope
import com.jydd.singlekotlinmvvm.comm.base.BaseLiveData
import com.jydd.singlekotlinmvvm.comm.base.BaseViewModel
import com.jydd.singlekotlinmvvm.comm.repo.UserDataSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * created by 韦敏敏
 * on 2020/1/21
 */
class LoginViewModel(
    private val userRepo : UserDataSource
) : BaseViewModel(){
    private val _signInResult : BaseLiveData<SignInResult> = BaseLiveData()
    val signInResult: BaseLiveData<SignInResult>
        get() = _signInResult
    fun signIn(username : String, password : String){
        userRepo.setUserInfo(username, password)
        viewModelScope.launch(Dispatchers.IO) {
            userRepo.run {
                authToken(
                    onSuccess = {
                        _signInResult.update(SignInResult.SUCCESS)
                    },
                    onError = {
                        _signInResult.update(SignInResult(1, it.message))
                        it.printStackTrace()
                    }
                )
            }

        }
    }

    data class SignInResult(
        val code : Int = -1,
        val error: String? = null
    ){
        companion object {
            val SUCCESS = SignInResult(0)
        }
    }
}